<?php


namespace Api\Http\Controllers;


use Alipay\OpenAPISDK\Api\AlipayFundTransUniApi;
use Alipay\OpenAPISDK\Util\AlipayConfigUtil;
use Alipay\OpenAPISDK\Util\Model\AlipayConfig;
use Alipay\OpenAPISDK\Util\Model\CustomizedParams;
use Api\traits\ApiResponse;
use GuzzleHttp\Client;
use Alipay\OpenAPISDK\ApiException;
use Alipay\OpenAPISDK\Model\AlipayFundTransUniTransferDefaultResponse;
use Alipay\OpenAPISDK\Model\AlipayFundTransUniTransferModel;
use Alipay\OpenAPISDK\Model\AlipayFundTransUniTransferResponseModel;
use Alipay\OpenAPISDK\Model\SignData;
use Alipay\OpenAPISDK\Model\Participant;
use Illuminate\Support\Facades\Log;

/**
 * @group 用户模块
 *
 * @subgroup 用户管理
 * @subgroupDescription CatchAdmin 后台用户管理
 *
 */
class AlipayController extends Controller
{
    use ApiResponse;


    private function getAlipayConfig()
    {
        $privateKey = file_get_contents(public_path('alipay/AlipayPrivate.txt'));
        $alipayConfig = new AlipayConfig();
        $alipayConfig->setServerUrl('https://openapi.alipay.com');
        $alipayConfig->setAppId('2021004193643218');
        $alipayConfig->setPrivateKey($privateKey);
        $alipayConfig->setAppCertPath(public_path('alipay/appCertPublicKey_2021004193643218.crt'));
        $alipayConfig->setAlipayPublicCertPath(public_path('alipay/alipayCertPublicKey_RSA2.crt'));
        $alipayConfig->setRootCertPath(public_path('alipay/alipayRootCert.crt'));
        return $alipayConfig;
    }

    public function transferToUser($account,$money,$realName)
    {
        $alipayConfigUtil = new AlipayConfigUtil($this->getAlipayConfig());
        // 构造请求参数以调用接口
        $apiInstance = new AlipayFundTransUniApi(
            new Client()
        );
// 设置AlipayConfigUtil
        $apiInstance->setAlipayConfigUtil($alipayConfigUtil);
        $data = new AlipayFundTransUniTransferModel();

// 设置商家侧唯一订单号
        $data->setOutBizNo(uniqid());

// 设置订单总金额
        $data->setTransAmount((string)$money);

// 设置描述特定的业务场景
        $data->setBizScene("DIRECT_TRANSFER");

// 设置业务产品码
        $data->setProductCode("TRANS_ACCOUNT_NO_PWD");

// 设置转账业务的标题
        $data->setOrderTitle("速速寄提现");

// 设置收款方信息
        $payeeInfo = new Participant();
        $payeeInfo->setIdentity($account);
        $payeeInfo->setIdentityType("ALIPAY_LOGON_ID");
        $payeeInfo->setName($realName);
        $data->setPayeeInfo($payeeInfo);


        try {
            $result = $apiInstance->transfer($data);
            return $result;
        } catch (ApiException $e) {
            Log::error($e->getMessage());
            return $e->getResponseBody();
        }
    }
}
